﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;

namespace NCommander
{
	public partial class NewService : Form
	{
		public NewService()
		{
			InitializeComponent();
		}

		private void _path_Validating( object sender, CancelEventArgs e )
		{
			if( !File.Exists( _path.Text ) )
			{
				_errorProvider.SetIconAlignment( _path, ErrorIconAlignment.MiddleLeft );
				_errorProvider.SetError( _path, "File not found!" );
			}
			else
				_errorProvider.Clear();
		}

		private void _browse_Click( object sender, EventArgs e )
		{
			if( _findExecutableDialog.ShowDialog( this ) != DialogResult.OK )
				return;

			_path.Text = _findExecutableDialog.FileName;
			_errorProvider.Clear();
		}

		private void _ok_Click( object sender, EventArgs e )
		{
			var path = Path.Combine( Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location ), string.Join( Path.DirectorySeparatorChar.ToString(), new[] { "Contents", "Services", "srvany.exe" } ) );
			
			if( !_emulation.Checked )
				path = _path.Text;

			var manager = Win32.OpenSCManager( null, null, Win32.ServiceControlManagerAccessRights.SC_MANAGER_ALL_ACCESS );

			int tag;
			var service = Win32.CreateService( manager, _serviceName.Text, _displayName.Text, Win32.ServiceAccessRights.SERVICE_ALL_ACCESS, Win32.ServiceType.SERVICE_WIN32_OWN_PROCESS, Win32.ServiceStartType.SERVICE_AUTO_START, Win32.ServiceErrorControl.SERVICE_ERROR_IGNORE, path, "", out tag, _dependencies.Text, _account.SelectedItem.ToString(), null );

			Win32.CloseServiceHandle( manager );
		}

	}
}
